<template>
  <x-layout-main class="m-system-authority">
    <n-grid :x-gap="10">
      <!--列表-->
      <n-gi :span="12">
        <n-card
          :segmented="{ content: true }"
          :bordered="false"
          size="small"
          header-style="position: sticky; top: 0; background-color: #fff; z-index: 3;"
        >
          <template #header>资源项列表</template>
          <template #header-extra>
            <x-button icon="icon-037" type="primary" @click="onAdd"> 新建 </x-button>
          </template>
          <n-spin :show="loading">
            <n-tree
              v-if="list"
              :data="list"
              :cancelable="false"
              :selected-keys="selectedKeys"
              :render-suffix="renderSuffix"
              :render-label="renderLabel"
              block-line
              selectable
              @update:selected-keys="onChangeTree"
            />
          </n-spin>
        </n-card>
      </n-gi>
      <!--编辑-->
      <n-gi :span="12">
        <n-card :segmented="{ content: true }" :bordered="false" size="small" style="position: sticky; top: 12px">
          <template #header>
            <n-space>
              <x-icon name="icon-029" />
              <span>{{ editTitle }}</span>
            </n-space>
          </template>
          <n-alert type="info">从左侧列表选择一项后，进行编辑</n-alert>
          <div class="edit">
            <x-form
              v-if="currentRow"
              ref="formRef"
              v-model:model="currentRow"
              :rules="rules"
              :label-width="120"
              :disabled="isEditDisabled"
              label-placement="left"
            >
              <n-form-item label="资源编码" path="resourceName">
                <n-input
                  v-model:value="currentRow.resourceName"
                  placeholder="建议使用前端的router唯一标识，如：SystemAuthority"
                />
              </n-form-item>
              <n-form-item label="资源描述" path="resourceDescription">
                <n-input v-model:value="currentRow.resourceDescription" placeholder="请输入资源描述" />
              </n-form-item>
              <n-form-item label="资源类型" path="resourceType">
                <n-radio-group v-model:value="currentRow.resourceType">
                  <n-radio-button v-for="item in dictionary['RESOURCE_TYPE']" :key="item.value" :value="item.value">
                    {{ item.label }}
                  </n-radio-button>
                </n-radio-group>
              </n-form-item>
              <n-form-item label="父级" path="parentId">
                <n-tree-select
                  v-model:value="currentRow.parentId"
                  :options="list"
                  filterable
                  clearable
                  placeholder="请选择父级"
                />
              </n-form-item>
              <n-form-item label="权限范围开关" path="dataStatus">
                <n-switch v-model:value="currentRow.dataStatus" :checked-value="1" :unchecked-value="0"> </n-switch>
              </n-form-item>
              <n-form-item label="排序" path="resourceSort">
                <n-input-number
                  v-model:value="currentRow.resourceSort"
                  style="width: 100%"
                  placeholder="请输入排序值"
                />
              </n-form-item>
              <n-form-item label="备注" path="remark">
                <n-input v-model:value="currentRow.remark" placeholder="请输入备注" />
              </n-form-item>
              <n-form-item style="display: flex; justify-content: center">
                <x-button type="primary" ghost @click="resetForm">重置</x-button>
                <x-button :loading="loading" type="primary" @click="submitForm">保存</x-button>
              </n-form-item>
            </x-form>
          </div>
        </n-card>
      </n-gi>
    </n-grid>
  </x-layout-main>
</template>

<script lang="ts">
  import { computed, defineComponent, reactive, toRefs, h, ref, watch } from 'vue'
  import {
    NGrid,
    NGi,
    NCard,
    NSpace,
    NAlert,
    NFormItem,
    NInput,
    NRadioGroup,
    NRadioButton,
    NTree,
    NTreeSelect,
    NSpin,
    NTag,
    NPopconfirm,
    NInputNumber,
    NSwitch,
    useMessage
  } from 'naive-ui'
  import { XIcon, XLayoutMain, XForm, XButton } from '@/components'
  import { useStore } from '@/store'
  import { useAuthority, useDictionary } from '@/hooks'
  import { getTreeItem } from '@/utils'
  import { useRoute } from 'vue-router'

  export default defineComponent({
    name: 'SystemAuthority',
    components: {
      NGrid,
      NGi,
      NCard,
      NSpace,
      NAlert,
      NFormItem,
      NInput,
      NRadioGroup,
      NRadioButton,
      NTree,
      NTreeSelect,
      NSpin,
      NInputNumber,
      XLayoutMain,
      XIcon,
      XForm,
      NSwitch,
      XButton
    },
    setup() {
      const $authority = useAuthority()
      const $route = useRoute()
      const $store = useStore()
      const $message = useMessage()
      const $dictionary = useDictionary()
      $dictionary.get('RESOURCE_TYPE')
      const formRef: any = ref(null)
      const tableElRef: any = ref(null)
      const $state: any = reactive({
        // 区分类型：1-运营后台资源；2-商家后台资源；
        platformType: computed(() => {
          switch ($route.name) {
            case 'SystemAuthority':
              return 1
            case 'MerchantAuthority':
              return 2
            default:
              return 1
          }
        }),
        list: null,
        loading: false,
        currentRow: null,
        selectedKeys: [],
        rules: {
          resourceName: {
            required: true,
            message: '请输入资源编码',
            trigger: 'blur'
          },
          resourceDescription: {
            required: true,
            message: '请输入资源描述',
            trigger: 'blur'
          },
          resourceType: {
            required: true,
            type: 'number',
            message: '请选择资源类型',
            trigger: 'change'
          },
          resourceSort: {
            required: true,
            type: 'number',
            message: '请输入排序值',
            trigger: 'blur'
          }
        },
        editTitle: computed(() => {
          return $state.currentRow ? ($state.currentRow.type ? '编辑资源项' : '新建资源项') : '新建/编辑资源项'
        }),
        dictionary: computed(() => {
          return $store.getters.dictionary
        }),
        isEditDisabled: computed(() => {
          // return !$authority.is(['店铺资源项-编辑', '系统资源项-编辑'])
          return false
        })
      })

      // watch
      watch(
        () => $route.name,
        () => {
          onInquiry()
        }
      )

      // 主动查询
      const onInquiry = () => {
        $state.loading = true
        $store
          .dispatch('system/getSystemAuthority', {
            platformType: $state.platformType
          })
          .then((res) => {
            $state.loading = false
            $state.list = res.data
          })
          .catch(() => {
            $state.loading = false
          })
      }
      onInquiry()

      // 编辑
      const onChangeTree = (row: number[]) => {
        formRef.value && formRef.value.resetDefaultValue()
        $state.selectedKeys = row
        $state.currentRow = getTreeItem($state.list, row[0])
      }

      // 新增
      const onAdd = () => {
        formRef.value && formRef.value.resetDefaultValue()
        $state.selectedKeys = []
        $state.currentRow = {
          resourceName: null,
          description: null,
          resourceType: null,
          parentId: null,
          remark: null,
          dataStatus: 0,
          resourceSort: 0,
          platformType: $state.platformType
        }
      }
      // 删除
      const handleRemoveRow = (row: any) => {
        $state.loading = false
        $store
          .dispatch('system/removeSystemAuthority', {
            id: row.id
          })
          .then(() => {
            onInquiry()
            $message.success('执行成功')
          })
          .catch(() => {
            $state.loading = false
          })
      }
      // 格式化节点后缀
      const renderSuffix = (res: any) => {
        return res.option.children
          ? null
          : h(
              NPopconfirm,
              {
                onPositiveClick: () => {
                  handleRemoveRow(res.option)
                }
              },
              {
                default: () => '确定要删除此资源项？',
                trigger: () =>
                  h(
                    XButton,
                    {
                      text: true,
                      type: 'error',
                      onClick: (e: any) => {
                        e.stopPropagation()
                      }
                    },
                    { default: () => '删除' }
                  )
              }
            )
      }
      // 格式化节点后缀
      const renderLabel = (res: any) => {
        const option = res.option
        const RESOURCE_TYPE = $state.dictionary['RESOURCE_TYPE']
        const TAG_TYPE = {
          1: 'primary',
          2: 'success',
          3: 'info',
          4: 'default',
          5: 'warning',
          6: 'error'
        }
        return h(NSpace, null, () => [
          h('span', null, option.label),
          h(
            NTag,
            { type: TAG_TYPE[String(option.resourceType)], round: true, size: 'small' },
            {
              default: () => {
                return RESOURCE_TYPE
                  ? RESOURCE_TYPE.find((item: any) => item.value === option.resourceType).label
                  : null
              }
            }
          )
        ])
      }

      // 重置
      const resetForm = () => {
        formRef.value.resetFields()
      }

      // 提交
      const submitForm = () => {
        formRef.value.validate((errors: []) => {
          if (!errors) {
            $state.loading = true
            $store
              .dispatch('system/setSystemAuthority', $state.currentRow)
              .then(() => {
                $message.success('执行成功')
                $state.loading = false
                onInquiry()

                // 新建成功后，清除右则数据
                if ($state.currentRow.id) {
                  // 编辑成功后更新初始重置值
                  formRef.value && formRef.value.resetDefaultValue($state.currentRow)
                } else {
                  // 新建成功后，清除右则数据
                  onAdd()
                }
              })
              .catch(() => {
                $state.loading = false
              })
          } else {
            $message.warning('验证失败，请填写完整信息')
          }
        })
      }
      return {
        ...toRefs($state),
        formRef,
        tableElRef,
        onInquiry,
        onAdd,
        onChangeTree,
        renderLabel,
        renderSuffix,
        resetForm,
        submitForm
      }
    }
  })
</script>

<style lang="scss" scoped>
  .m-system-authority {
    .edit {
      padding-top: 20px;
    }
  }
</style>
